﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebTest.ControlTest
{
    public class ControlMapping
    {
        public static void ModelToControl(object model, Panel panel_mapping)
        {
            Type type = model.GetType();
            foreach (PropertyInfo pi in type.GetProperties())
            {
                object value = pi.GetValue(model, null);
                string name = pi.Name; //获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
                //获得属性的类型,进行判断然后进行以后的操作,例如判断获得的属性是整数
                //if (value.GetType() == typeof(int))
                //{
                //    //进行你想要的操作
                //    //Response.Write(name);
                //}

                Control control = panel_mapping.FindControl(name);
                if (control is TextBox)
                {
                    TextBox textBox = (TextBox)control;
                    textBox.Text = value.ToString();
                }
            }
        }

        public static void ControlToModel(object model, Panel panel_mapping)
        {
            Type type = model.GetType();
            foreach (Control control in panel_mapping.Controls)
            {
                if (control is TextBox)
                {
                    TextBox textBox = (TextBox)control;
                    string value = textBox.Text;
                    string fieldName = textBox.ID;


                    object objValue = Convert.ChangeType(value, type.GetProperty(fieldName).PropertyType);
                    type.GetProperty(fieldName).SetValue(model, objValue, null);

                }
            }
        }
    }
}